package com.zw.yzk.kabu.data.repository;

import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.cache.store.UserStore;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.network.ServiceGenerator;
import com.zw.yzk.kabu.data.network.entity.FollowListEntity;
import com.zw.yzk.kabu.data.network.service.FollowListService;
import com.zw.yzk.kabu.data.network.task.GetFollowTask;

import javax.inject.Inject;

import rx.Observable;
import rx.functions.Func1;

/**
 * Created by zhanwei on 2017/1/12.
 */

public class FollowListRepository extends CommonRepository {

    private int totalCount;

    @Inject
    public FollowListRepository() {
        totalCount = GetFollowTask.DEFAULT_FOLLOW_COUNT_PER_PAGE;
    }


    @Override
    protected Observable connectServer(Task task) {
        FollowListService service = ServiceGenerator.createService(FollowListService.class);
        GetFollowTask getFollow = (GetFollowTask) addToken(task);

        if (getFollow.start >= totalCount) {
            FollowListEntity entity = new FollowListEntity();
            //已经全部加载，直接返回空列表
            entity.errCode = Constant.RESULT_OK;
            entity.result.total = totalCount;

            return Observable.just(entity);
        } else {
            return service.getFollowList(
                    getFollow.ownerId,
                    getFollow.userId,
                    getFollow.accessToken,
                    getFollow.start,
                    getFollow.size);
        }
    }

    @Override
    protected Func1<FollowListEntity, Observable> getServerData() {
        return new Func1<FollowListEntity, Observable>() {
            @Override
            public Observable call(FollowListEntity entity) {
                totalCount = entity.result.total;
                updateUser(entity);
                return Observable.just(entity);
            }
        };
    }

    /**
     * 更新user信息
     *
     * @param entity
     */
    private void updateUser(FollowListEntity entity) {
        User user = DataBaseManager.getInstance().getLoginUser();
        if(user == null) {
            return;
        }
        user.setTotalFans(entity.result.total);
        new UserStore().updateUserInfo(user);
    }
}
